package test.utility;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/* @ 2023-06-26
 * sql集合
 */
public class SqlCollections {
    private static List<String> sqls = new ArrayList<String>();
    private static String iGNORE_PRE = "--";
    private static String BEGIN_KEY[] = {"SELECT", "WITH",
            "INSERT", "UPDATE", "DELETE",
            "CREATE", "DROP",
            "BEGIN", "DECLARE"};

    public SqlCollections(String sqlfile) {
        File file = new File(sqlfile);
        if (!file.isDirectory()) {
            readSQLFile(file);
        } else {
//仅考虑该目录下后缀名为sql的文件
            File[] sqlfiles = file.listFiles((pathname) -> pathname.getName().toLowerCase().endsWith("sql"));
            for (File tmp : sqlfiles) {
                readSQLFile(tmp);
            }
        }
    }

    private static void readSQLFile(File sqlfile) {
        InputStreamReader read = null;
        BufferedReader reader = null;
        String line = ""; //行缓冲区
        StringBuilder sql = new StringBuilder();//sql缓冲区

        try {
            read = new InputStreamReader(new FileInputStream(sqlfile));
        } catch (FileNotFoundException e) {
            System.err.println("[Error:][read file fail] " + sqlfile);
        }
        reader = new BufferedReader(read);
        try {
            while ((line = reader.readLine()) != null) {
                if (!line.startsWith(iGNORE_PRE)) { //忽略注释
                    if (isNewSql(line)) { //如果是新sql,那么已有的sql需要加入集合
                        if (sql.length() != 0) {
                            sqls.add(sql.toString());
                        }
                        sql.setLength(0); //清空sql缓冲区
                    }
                    sql.append(line);
                }
            }
            if (sql.length() != 0) { //读取文件结束后, sql缓冲区内容也要加入集合
                sqls.add(sql.toString());
            }
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                read.close();
            } catch (IOException e) {
// TODO Auto-generated catch block
            }
        }
    }

    //判定一行是否是新sql
    private static boolean isNewSql(String line) {
        boolean flag = false;
        String tmp = line.toUpperCase();
        for (String key : BEGIN_KEY) {
            if (tmp.startsWith(key)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    public List<String> getSqls() {
        return sqls;
    }

    public int getSqlCount() {
        return sqls.size();
    }
}
